package com.czx.drivingtest.utils;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;

import java.util.Date;
import java.util.Map;

/**
 * jwt工具类
 * 用于生成和校验token
 * @author czx
 * @date 2020/7/13 10:14
 */
public class JwtUtils {
    /**
     * 密钥
     */
    private static final String secret = "chendada";
    /**
     * 7天的毫秒
     */
    public static final long expireIn = 604800000L;

    /**
     * 创建一个token
     * @param userId
     * @return
     */
    public static String createToken(long userId) {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        return JWT.create()
                .withExpiresAt(DateUtil.offsetDay(new Date(), 7))
                .withClaim("userId", userId)
                .sign(algorithm);
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public static boolean verifyToken(String token) {
        Date expiresAt = JWT.decode(token).getExpiresAt();
        return DateTime.now().isBefore(expiresAt);
    }

    /**
     * 从token中解析出用户id
     * @param token
     * @return
     */
    public static long analysisUserId(String token) {
        Claim claim = JWT.decode(token).getClaim("userId");
        return claim.asLong();
    }

}
